//
//  LoaderVC.swift
//  Example
//
//  Created by remy on 2019/4/8.
//  Copyright © 2019 com.Risac. All rights reserved.
//

class LoaderVC: BaseVC, DataLoadable {
    private lazy var tl: DataLoader = DataLoader(target: self)
    private lazy var tp: TablePack = TablePack(frame: self.bodyViewFrame) {
        $0.view.rowHeight = 88.0
        $0.action.heightCalculate = .none
    }
    private lazy var cl: DataLoader = DataLoader(target: self)
    private lazy var cp: CollectionPack = CollectionPack(frame: self.bodyViewFrame)
    
    override func viewDidLoad() {
        super.viewDidLoad()
        topBarView.centerItem = .text(title)
        // DataLoader+TablePack
        tl.setPack(tp)
        tl.setPackRefresh(.pullAndLoad)
        tp.view.backgroundColor = FlatColor.amethyst
        tp.view.height = (Size.screenHeight - Size.topHeight) * 0.5
        tp.action.handle(.tap, cellItemClass: TableItem.self) {
            Risac.print($1)
        }
        tp.action.handle(.display, cellItemClass: TableItem.self) {
            Risac.print($1)
        }
        self.view.addSubview(tp.view)
        // DataLoader+CollectionPack
        cl.setPack(cp)
        cl.setPackRefresh(.loadAndPull)
        cp.view.backgroundColor = FlatColor.carrot
        cp.view.top = tp.view.bottom
        cp.view.height = (Size.screenHeight - Size.topHeight) * 0.5
        self.view.addSubview(cp.view)
        tl.pageTurn()
        cl.pageTurn()
    }
    
    func dataLoadPrepare(loader: DataLoader) {
        if loader === tl {
            var params: [String: Any] = [:]
            params["page"] = loader.pageInfo.index
            params["pageSize"] = loader.pageInfo.size
            params["countryId"] = "COUNTRY_225"
            loader.target = API.NORMAL_GET("schools", params)
        } else if loader === cl {
            var params: [String: Any] = [:]
            params["page"] = loader.pageInfo.index
            params["pageSize"] = loader.pageInfo.size
            params["countryId"] = "COUNTRY_225"
            loader.target = API.NORMAL_GET("schools", params)
        }
    }
    
    func dataLoadResult(loader: DataLoader, result: NetworkManager.ResultType) {
        if loader === tl {
            if case let .success(jsonData) = result {
                let data = jsonData["data"]["data"].arrayValue
                var items: [TableItem] = []
                data.forEach {
                    items.append(TableItem(data: $0))
                }
                tp.model.add(items)
                tp.view.reloadData()
            } else if case let .failure(error) = result {
                RisacPop.toast(error.localizedDescription) {
                    $0.stayTime = 2.0
                }
            }
        } else if loader === cl {
            if case let .success(jsonData) = result {
                let data = jsonData["data"]["data"].arrayValue
                var items: [ListItem] = []
                data.forEach {
                    items.append(ListItem(data: $0))
                }
                if cp.model.sectionItems.count == 0 {
                    cp.model.add(ListSection())
                }
                cp.model.insert(items, at: IndexPath(row: 0, section: 0))
                cp.view.reloadData()
            } else if case let .failure(error) = result {
                RisacPop.toast(error.localizedDescription) {
                    $0.stayTime = 2.0
                }
            }
        }
    }
}

struct TableItemModel: DataModelable {
    var chineseName: String = ""
    var englishName: String = ""
    var logoURL: String = ""
    
    init(json: JSON?) {
        guard let json = json else { return }
        chineseName = json["chineseName"].stringValue
        englishName = json["englishName"].stringValue
        logoURL = json["logo"].stringValue
    }
}

class TableItem: TableCellItem {
    init(data: JSON) {
        super.init()
        self.model = TableItemModel.toModel(data)
        cellClass = TableItemCell.self
        cellHeight = 44.0
    }
    
    override func reload() {}
}

class TableItemCell: TableCell {
    private var titleLabel: UILabel!
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        contentView.backgroundColor = .white
        titleLabel = UILabel(textColor: .black, fontSize: 14.0)
        contentView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints {
            $0.left.equalTo(16.0)
            $0.right.equalTo(-16.0)
            $0.centerY.equalToSuperview()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func updateCell(cellItem: TableCellItem?) {
        if let model = cellItem?.model as? TableItemModel {
            titleLabel.text = model.chineseName + "(\(model.englishName))"
        }
    }
}

class CollectionItemModel1: DataModelable {
    var chineseName: String = ""
    var englishName: String = ""
    
    required init(json: JSON?) {
        guard let json = json else { return }
        chineseName = json["chineseName"].stringValue
        englishName = json["englishName"].stringValue
    }
}
class CollectionItemModel2: CollectionItemModel1 {
    var logoURL: String = ""
    
    required init(json: JSON?) {
        super.init(json: nil)
        guard let json = json else { return }
        chineseName = json["chineseName"].stringValue
        englishName = json["englishName"].stringValue
        logoURL = json["logo"].stringValue
    }
}

class ListSection: CollectionSectionItem {
    override init() {
        super.init()
        sectionHeaderHeight = 40.0
        sectionFooterHeight = 20.0
        sectionHeaderClass = ListViewHeader.self
        sectionFooterClass = ListViewFooter.self
        lineSpacing = 5.0
        itemSpacing = 30.0
        sectionInset = UIEdgeInsets(top: 5.0, left: 20, bottom: 5.0, right: 20)
    }
}

class ListViewHeader: CollectionSection {
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = .yellow
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

class ListViewFooter: CollectionSection {
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = .gray
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

class ListItem: CollectionCellItem {
    init(data: JSON) {
        super.init()
        self.model = CollectionItemModel2.toModel(data)
        cellClass = ListViewCell.self
        cellSize = CGSize(width: 64.0, height: 64.0)
    }
}

class ListViewCell: CollectionCell {
    private var imageView: UIImageView!
    private var titleLabel: UILabel!
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        contentView.backgroundColor = .blue
        imageView = UIImageView(frame: CGRect(x: 11.0, y: 0.0, width: 42.0, height: 42.0))
        imageView.cornerRadius(21.0)
        imageView.contentMode = .scaleAspectFit
        contentView.addSubview(imageView)
        titleLabel = UILabel(textColor: .black, fontSize: 14.0, alignment: .center)
        contentView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func updateCell(cellItem: CollectionCellItem?) {
        if let model = cellItem?.model as? CollectionItemModel2 {
            titleLabel.text = model.chineseName
            imageView.kf.setImage(with: URL(string: model.logoURL))
        }
    }
}
